package com.awccis.driver.controller;

import cn.jpush.api.push.model.PushPayload;
import com.awccis.admin.model.pay.PaySimpleInfoBean;
import com.awccis.admin.service.AdminService;
import com.awccis.common.controller.BaseUploadController;
import com.awccis.common.pool.DriverPool;
import com.awccis.common.utils.*;
import com.awccis.driver.model.*;
import com.awccis.driver.model.car.CarInfo;
import com.awccis.driver.service.DriverService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: 纯牛奶丶
 * @Date: 2018-03-30 0030 下午 05:10
 * @Since: 1.0
 * @Decription: 司机端控制接口，司机注册，登录，获取信息。
 **/
@Controller
@RequestMapping(value = "/driver", method = RequestMethod.POST)
public class DriverController extends BaseUploadController {


    /**
     * 日志打印对象
     */
    private Logger logger = LoggerFactory.getLogger(DriverController.class);

    @Resource
    private DriverService driverService;
    @Resource
    private AdminService adminService;

    @Resource
    private DriverInfo driverInfo;
    @Resource
    private CarInfo carInfo;
    @Resource
    private StatusBean statusBean;

    /**
     * spring线程池
     */
    @Resource
    ThreadPoolTaskExecutor cacheExecutor;
    /**
     * 接受浏览器发送的driver的json格式的登陆数据
     * 通过driverService验证数据库中的登录数据
     *
     * @param driver {"driverNickName":23, "driverPasswd":123123,"driverPhone":"+861234567890"}
     * @return {"result": true, "message": ""}
     */
    @RequestMapping(value = "/driverLogin", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object driverLogin(@RequestBody DriverLoginInfo driver) {
        logger.info("driver司机登陆数据信息：" + driver.toString());
        Map<String, Object> map = new HashMap<>(2);
        System.out.println(driver.toString());

        int nickName = driver.getDriverNickName();
        //判断登录名是否存在
        boolean loginNameExists = driverService.selectLoginNameExists(nickName);
        if (loginNameExists) {
            //判断账户是否已经登录
            boolean onlineStatus = DriverPool.isContainByNickname(nickName);
            if (onlineStatus) {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "用户已经登录！");
            } else {
                DriverInfo result;
                try {
                    driver.setDriverPasswd(MD5Utils.MD5(driver.getDriverPasswd()));
                    result = driverService.checkDriverInfo(driver);
                    logger.info("driver司机登陆数据信息----> 用户登陆需要返回的信息：" + result.toString());
                } catch (NullPointerException e) {

                    logger.warn("driver登录验证结果空指针异常：" + e);

                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, "密码错误！");
                    return map;
                }

                boolean isFrozen = result.getDriverStatus() == 1;
                if (isFrozen) {
                    if (result.getDriverIsChecked() == 1) {
                        map.put(Constants.MAP_KEY_RESULT, false);
                        map.put(Constants.MAP_KEY_MESSAGE, "您的账户未通过审核!请及时联系客服人员!");
                    } else {
                        map.put(Constants.MAP_KEY_RESULT, false);
                        map.put(Constants.MAP_KEY_MESSAGE, "注册成功，等待后台审核中!");
                    }
                    return map;
                }

                String driverName = result.getDriverName();
                if (driverName != null || !"".equals(driverName)) {
                    statusBean.setDriverId(result.getDriverId());
                    statusBean.setStatusId(0);

                    //查看星级
                    int i = driverService.selectIntegralCount(statusBean);
                    result.setStarLevel(i == 0 ? 5 : i);
                    logger.info("driver登录信息验证结果：" + result);
                    map.put(Constants.MAP_KEY_RESULT, true);
                    map.put(Constants.MAP_KEY_MESSAGE, result);
                } else {
                    map.put(Constants.MAP_KEY_RESULT, false);
                    map.put(Constants.MAP_KEY_MESSAGE, Constants.MAP_VALUE_LOGIN_ERROR);
                }
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "登录名不存在！");
        }

        return map;
    }

    @RequestMapping(value = "/upDriverPlace")
    @ResponseBody
    public  void upDriverPlace(@RequestParam  String driverId,@RequestParam  String longitude,@RequestParam String latitude){
        boolean b = DriverPool.updateLocation(Integer.parseInt(driverId), Double.parseDouble(latitude), Double.parseDouble(longitude));
        if(!b){
            logger.info(driverId+"---用户不存在");
        }

    }

    @GetMapping(value = "/testPropels")
    @ResponseBody
    public String testPropels(@RequestParam String id){
        PushPayload pushPayload = MessagePushUtil.pushAndroidAndIosByAlias(id, "推送订单", "订单推送了","乘客信息");
        MessagePushUtil.sendPushTryCatch(pushPayload);
        return  id+"--推送了订单";
    }

    /**
     * 接收浏览器发送的driver的注册信息，
     * 向数据库中添加这些注册信息，并且返回注册结果
     *
     * @param combineBean {"": }
     * @return {"result": true, "message": }
     */
    @RequestMapping(value = "/driverRegister", produces = "application/json; charset=UTF-8")
    public @ResponseBody
    Object driverRegister(@RequestBody CombineBean combineBean) {
        logger.info("driver司机注册信息：" + combineBean.toString());
        Map<String, Object> map = new HashMap<>(2);

        driverInfo = combineBean.getDriverInfo();
        int nickName = driverService.getLastNickName() + 1;
        driverInfo.setDriverNickName(nickName);
        carInfo = combineBean.getCarInfo();

        //执行添加driver信息业务逻辑
        driverInfo.setDriverPasswd(MD5Utils.MD5(driverInfo.getDriverPasswd()));
        //注册之后设置成冻结状态(1),等待管理员审核
        driverInfo.setDriverStatus(1);
        driverService.insertDriverInfo(driverInfo);
        int driverId = driverInfo.getDriverId();
        carInfo.setDriverId(driverId);

        boolean result = driverService.insertCarInfoAndLocation(carInfo);
        if (result) {
            map.put(Constants.MAP_KEY_RESULT, result);
            map.put(Constants.MAP_KEY_MESSAGE, nickName);
            //发送短信的过程可能耗时较长，且无需将发送结果返回给前端，所以在子线程中执行
            cacheExecutor.execute(() -> {
                //注册成功后向管理员发短信通知审核
                String headMsg = "【AWCCIS】 \n E加家 平台信息\n";
                String infoMsg = "手机号为:"+driverInfo.getDriverPhone()+"的司机已成功注册，请及时审核。";
                String msgToAdmin = headMsg + infoMsg;
                String adminPhone = JsonUtil.getJsonConfigValue("adminPhone");
                String msgResult = SendMessageUtil.sendMessageTo(JsonUtil.getJsonConfigValue("adminPhone"), msgToAdmin);
                //String msgResult = "ok";
                logger.info("管理员手机号码："+adminPhone);
                logger.info("审核短信内容："+msgToAdmin);
                logger.info("审核短信nexmo返回结果："+msgResult);


            });
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "注册失败");
        }
        return map;
    }

    /**
     * driver上传图片
     *
     * @param request       请求参数
     * @param multipartFile 文件对象
     * @return {"imgPath": "/WEB-INF/upload/..........."}
     */
    @RequestMapping("/uploadImg")
    public @ResponseBody
    Map uploadImg(HttpServletRequest request, @RequestParam("uploadFile") MultipartFile multipartFile) {
        String fileName = "driverimg";
        return uploadFile(fileName, request, multipartFile);
    }

    /**
     * 更改状态信息,
     * 判断要更改的状态类型，并且判断更改的状态，执行不同的更改状态的业务操作     driver0023
     *
     * @param statusBean {"driverNickName":28, "flag":true, "statusType":"driverIsOnline"} {"driverId", "isReady"}
     * @return {"result": true}
     */
    @RequestMapping(value = "/updateStatus", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object updateStatus(@RequestBody StatusBean statusBean) {
        logger.info("driver司机更改状态信息：" + statusBean.toString());

        Map<String, Object> map = new HashMap<>(2);
        boolean flag = statusBean.isFlag();
        boolean result = false;
        if (flag) {
            statusBean.setStatusId(0);
        } else {
            statusBean.setStatusId(1);
        }
        //判断状态类型
        switch (statusBean.getStatusType()) {
            case Constants.DRIVER_STATUS:
                result = driverService.updateStatus(statusBean);
                break;
            case Constants.DRIVER_IS_CHECKED:
                //发送短信的过程可能耗时较长，且无需将发送结果返回给前端，所以在子线程中执行
                cacheExecutor.execute(() -> {
                    //审核成功后向司机发短信通知
                    String headMsg = "【AWCCIS】 \n E加家 平台信息\n";
                    String infoMsg = "您的账号已通过审核，可以正常登陆。";
                    String msgToDriver = headMsg + infoMsg;
                    String driverPhone = driverService.getDriverPhoneByNickName(statusBean.getDriverNickName());
                    String msgResult = SendMessageUtil.sendMessageTo(driverPhone, msgToDriver);
                    //String msgResult = "ok";
                    logger.info(msgResult);


                });
                result = driverService.updateIsChecked(statusBean);
                break;
            case Constants.DRIVER_IS_ONLINE:
                if(!flag){
                    DriverPool.deleteDriverByNickName(statusBean.getDriverNickName());
                }
                break;
            case Constants.DRIVER_IS_WORK:
                    DriverPool.updateIsWorkByNickName(statusBean.getDriverNickName(),flag);
                break;
            case Constants.DRIVER_INTEGRAL_COUNT:
                result = driverService.updateIntegralCount(statusBean);
                break;
            case "isReady":
                result = DriverPool.updateIsReadyByDriverId(statusBean.getDriverId(), flag);
            default:
                break;
        }
        map.put(Constants.MAP_KEY_RESULT, result);
        return map;
    }

    /**
     * 根据司机driverNickName查询信用积分,
     * 并根据不同积分，做出等级判断，返回给客户端
     *
     * @param statusBean {"driverNickName":1}
     * @return {"result": 5}直接返回星级等级
     */
    @RequestMapping(value = "/selectStarLevel", produces = "application/json; charset=UTF-8")
    public @ResponseBody
    Object selectStarLevel(@RequestBody StatusBean statusBean) {
        logger.info("查询司机的星级用户：" + statusBean.getDriverNickName());

        Map<String, Object> map = new HashMap<>();
        int count;
        if (statusBean.getDriverNickName() != 0) {
            try {
                count = driverService.selectIntegralCount(statusBean);
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, count);
            } catch (NullPointerException e) {
                logger.warn("信用积分空指针异常、请求值不存在：" + e);
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "请求值不存在！");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "查询失败！");
        }
        return map;
    }

    /**
     * 查询司机的个人信息，
     * 根据driverNickName查询司机的个人信息，driverNickName在司机登陆的时候存在前端
     *
     * @param loginInfo {"driverNickName":28}
     * @return {"result": "driverInfo"}
     */
    @RequestMapping(value = "/getDriverInfo", produces = "application/json; charset=UTF-8")
    public @ResponseBody
    Object getDriverInfo(@RequestBody DriverLoginInfo loginInfo) {
        logger.info("查询司机个人信息：" + loginInfo.toString());

        Map<String, Object> map = new HashMap<>(2);
        DriverInfo driverInfo;

        if (!Constants.EMPTY_STRING.equals(loginInfo.getDriverNickName())) {
            driverInfo = driverService.selectDriverInfo(loginInfo);
            map.put(Constants.MAP_KEY_RESULT, driverInfo);
        } else {
            map.put(Constants.MAP_KEY_RESULT, Constants.MAP_VALUE_ERROR);
        }
        return map;
    }

    /**
     * 获取司机的详细信息
     * @param hashMap {"driverId": 23}
     * @return {}
     */
    @RequestMapping(value = "/getDriverDetailInfo", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody Map getDriverDetailInfo(@RequestBody HashMap<String, Integer> hashMap){
        logger.info("获取司机的详细信息：" + hashMap);

        Map map = new HashMap(2);

        if(hashMap.get("driverId") != null){
            //AdminService adminService = new AdminServiceImpl();
            try {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, adminService.getDriverDetailInfo(Integer.parseInt(hashMap.get("driverId").toString())));
            } catch (NumberFormatException e) {
                logger.warn("获取司机详细信息异常：" + e);
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "请求参数异常！");
            }
        }else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值！");
        }
        return map;
    }

    /**
     * 通过driverId更改司机的详细信息
     * @param driverUpdateInfo driverUpdateInfo
     * @return {}
     */
    @RequestMapping(value = "/updateDriverDetailInfo", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody Map updateDriverDetailInfo(@RequestBody DriverUpdateInfo driverUpdateInfo ){
        logger.info("更改司机的详细信息： " + driverUpdateInfo.toString());

        Map map = new HashMap(2);
        if(driverUpdateInfo.getDriverId() != 0){
            Boolean result = driverService.updateDriverDetailInfoById(driverUpdateInfo);
            DriverPool.updateInfo(driverUpdateInfo);
            if (result){
                map.put(Constants.MAP_KEY_RESULT, result);
                map.put(Constants.MAP_KEY_MESSAGE, "更改成功！");
            }else {
                map.put(Constants.MAP_KEY_RESULT, result);
                map.put(Constants.MAP_KEY_MESSAGE, "更改失败！");
            }
        }else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "请求参数非法！");
        }
        return map;
    }

    /**
     * 更改司机的位置
     *
     * @param hashMap {"driverNickName":23, "driverId": 31, "longitude": 2.333333, "latitude": 2.3333, "locationName": "aaaa"}
     * @return {"result": true or false}
     */
    @RequestMapping(value = "/updateDriverLocation", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody
    Object updateDriverLocation(@RequestBody HashMap<String, Object> hashMap) {
        logger.info("更新driver司机的位置" + hashMap);
        Map<String, Object> map = new HashMap<>(2);

        String driverNickName = "driverNickName";
        String driverId = "driverId";
        if (hashMap.get(driverNickName) == null && hashMap.get(driverId) == null) {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值！");
            return map;
        }
        try {
//            boolean isOnline = driverService.selectLoginStatus(Integer.parseInt(hashMap.get(driverNickName).toString()));
            boolean isOnline = DriverPool.isContainByNickname(Integer.parseInt(hashMap.get(driverNickName).toString()));
            if (isOnline) {
                //更改司机地址
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, "更改成功！");
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "非法请求值!");
            }
        } catch (NumberFormatException e) {
            logger.warn("更新driver司机地址----> 获取司机driverId异常" + e);
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值！");
        }
        return map;
    }

    /**
     * 司机在运行中的展示简单信息
     * @param hashMap {"driverId": 31}
     * @return {}
     */
    @RequestMapping(value = "/driverSimpleInfo", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody Map driverSimpleInfo(@RequestBody HashMap<String, Integer> hashMap){
        logger.info("司机在运行中的展示简单信息需要的参数：" + hashMap);
        Map map = new HashMap();

        String id = "driverId";
        if(hashMap.get(id) != null){
            HashMap resultInfo = driverService.selectSimpleDriverInfo(hashMap);
            StatusBean statusBean = new StatusBean();
            statusBean.setDriverId(hashMap.get(id));
            int starLevel = driverService.selectIntegralCount(statusBean);
            resultInfo.put("starLevel", starLevel);
            map.put(Constants.MAP_KEY_RESULT, true);
            map.put(Constants.MAP_KEY_MESSAGE, resultInfo);
        }else{
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值");
        }
        return map;
    }

    /**
     * 司机获取本周需要交费的金额
     * @param paySimpleInfoBean {"driverId": 37, "payWeek": "2018年第22周"}
     * @return map
     */
    @RequestMapping(value = "/getNeedPay", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody Map getNeedPay(@RequestBody PaySimpleInfoBean paySimpleInfoBean){
        logger.info("司机获取本周需要交费的金额:" + paySimpleInfoBean.toString());

        Map map = new HashMap(2);
        int driverId = paySimpleInfoBean.getDriverId();
        String payWeek = paySimpleInfoBean.getPayWeek();
        if(driverId != 0 && payWeek != null){
            PaySimpleInfoBean resultInfo = driverService.getNeedPayInfo(paySimpleInfoBean);
            if(resultInfo == null){
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "本周不需要支付平台费用！");
            }else{
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, resultInfo);
            }
        }else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE, "非法请求值！");
        }
        return map;
    }


    /**
     * 司机确认自己的缴费记录
     * @param paySimpleInfoBean {“payId”: 113, "payTime":"20181........"，"driverId": 29}
     * @return map
     */
    @RequestMapping(value = "/submitPayRecord", produces = Constants.REQUEST_PRODUCES)
    public @ResponseBody Map submitPayRecord(@RequestBody PaySimpleInfoBean paySimpleInfoBean){
        logger.info("司机确认自己的缴费记录" + paySimpleInfoBean.toString());

        Map map = new HashMap(2);
        boolean b = DriverPool.isContainById(paySimpleInfoBean.getDriverId());
        if(b){
            boolean result = driverService.setNeedPay(paySimpleInfoBean);
            if(result){
                map.put(Constants.MAP_KEY_RESULT, result);
                map.put(Constants.MAP_KEY_MESSAGE, "缴费成功！");
            }else {
                map.put(Constants.MAP_KEY_RESULT, result);
                map.put(Constants.MAP_KEY_MESSAGE, "缴费失败！");
            }
        }else{
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE,"非法请求！");
        }
        return map;
    }

    /**
     * 查询缴费记录
     * @param requestMap { "driverId":111 }
     * @return
        {
            "result": true,
            "message": [
                {
                "payId": 11,
                "driverId": 1111,
                "payCost": 57.8,
                "payTime": 1530285996000,
                "payWeek": "2018年第25周",
                "payLow20Weeks": 0,
                "payNeedCost": 9.826,
                "driverName": "aaa",
                "driverPhone": "+8613811012138",
                "payIsPayed": 1,
                "payWeekOrder": 3,
                "payOrderCount": 0
                }
            ]
        }
     */
    @RequestMapping(value = "/getPayRecord", produces = Constants.REQUEST_PRODUCES)
    @ResponseBody
    public Object getPayRecord(@RequestBody HashMap<String,Object> requestMap) {
        Map<String,Object> map = new HashMap<>(2);
        int driverId = (int) requestMap.get("driverId");
        List<PayRecord> payRecord = driverService.getPayRecord(driverId);
        boolean isLogin = DriverPool.isContainById(driverId);
        //isLogin = true;//测试
        if (isLogin) {
            if (payRecord != null) {
                map.put(Constants.MAP_KEY_RESULT, true);
                map.put(Constants.MAP_KEY_MESSAGE, payRecord);
            } else {
                map.put(Constants.MAP_KEY_RESULT, false);
                map.put(Constants.MAP_KEY_MESSAGE, "没有查询到缴费记录");
            }
        } else {
            map.put(Constants.MAP_KEY_RESULT, false);
            map.put(Constants.MAP_KEY_MESSAGE,"非法请求！");
        }
        return map;
    }

    /**
     * 记录访问量
     */
    @RequestMapping(value = "/visitInfo", produces = "application/json; charset=UTF-8")
    public  @ResponseBody Object recordVisitInfo(@RequestBody Map requestMap, HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>();
        map.put("date",System.currentTimeMillis());
        map.put("os", requestMap.get("os"));
        map.put("model", requestMap.get("model"));
        map.put("ip", request.getRemoteAddr());
        driverService.recordVisitInfo(map);
        
        return requestMap;
    }
}